<?php

namespace app\common\model\xilujob;

use app\common\model\User;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;


class CompanyComment extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'xilujob_company_comment';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function member() {
        return $this->belongsTo('Member', 'user_id')->setEagerlyType(0);
    }

    public function company() {
        return $this->belongsTo('CompanyProfile', 'company_id')->setEagerlyType(0);
    }

    public function enterpriseinfo() {
        return $this->belongsTo('EnterpriseInfo', 'company_id','company_id')->setEagerlyType(0);
    }

    public static function init() {
        $updateCompanyScore = function($row) {
            $company_id = $row->company_id;
            $ret = Db::name('company_comment')->where('company_id',$company_id)
                ->whereNUll('deletetime')
                ->fieldRaw('sum(avg_score) as total, count(*) times')
                ->find();
            if($ret && $ret['times']>0) {
                $score = intval($ret['total'] / $ret['times']);
            }else {
                $score = 0;
            }
            Db::name('enterprise_info')->where('id',$company_id)->update(['avg_score'=>$score]);
        };
        self::afterInsert($updateCompanyScore);
        self::afterDelete($updateCompanyScore);
    }

    public static function addComment($params) {
        $hasComment = self::where('user_id',$params['user_id'])
            ->where('company_id', $params['company_id'])
            ->count()>0;
        if($hasComment) {
            throw new Exception('您已经发布过评论');
        }
        try {
            $comment = new self();
            $params['avg_score'] = intval(($params['environment_score']+$params['benefit_score']+$params['opportunity_score'])/3);
            $params['content'] = array_get($params,'content', '');
            $params['status'] = 1;
            $ret = $comment->save($params);
            if ($ret === false) {
                throw new Exception($comment->getError());
            }
            return $comment;
        }catch (\Exception $e) {
            return $e;
        }

    }
}
